﻿using System;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using System.Text;
using System.Net.Http.Headers;
using System.Threading;
using System.Data.OleDb;
using System.Data;
using System.Collections.Generic;

namespace _12_AI
{
    public partial class Form1 : Form
    {
        public Form1() { InitializeComponent(); }
        static List<string> list = new List<string>();
        private async void button1_Click(object sender, EventArgs e)//AI回答
        {
            string question;

            if (dataGridView1.RowCount == 0) { return; }
            toolStripProgressBar1.Maximum = dataGridView1.RowCount;
            toolStripProgressBar1.Value = 0;
            for (int r = 0; r < dataGridView1.RowCount - 1; r++)
            {
                //已有数值则跳过
                if (dataGridView1.Rows[r].Cells[1].Value.ToString() != "") { continue; }

                //获得问题
                question = $"根据存货编码表格里的存货代码和规格型号，找到{dataGridView1.Rows[r].Cells[0].Value.ToString()}的对应编码，直接输出存货编码的结果值就行，无需进行其他描述";

                //AI回答
                Coze.Coze1(question);

                var client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer pat_20D4Uu1hM5b5lYFijNp3vORK3gG7nIP7f7k1cVnSheMVSbR3oUtAfZAf8jveXZyM");
                var requestData = new
                {
                    auto_save_history = true,
                    stream = false,
                    user_id = "me",
                    bot_id = "7489376497380343820",
                    additional_messages = new[]
                    {
                    new{
                            role= "user" ,
                            content=question
                        }
                    }
                };//请求参数

                var jsonContent = JsonConvert.SerializeObject(requestData);//转换成json格式
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                var response = await client.PostAsync($"https://api.coze.cn/v3/chat?", content);
                dynamic responseContet = await response.Content.ReadAsStringAsync();

                dynamic result = JsonConvert.DeserializeObject(responseContet);

                string str_chat_id = result.data.id;
                string str_conversation_id = result.data.conversation_id; ;

                Coze2(str_chat_id, str_conversation_id);

                //dataGridView1.Rows[r].Cells[1].Value = answer;

                //更新进度条
                toolStripProgressBar1.Value += 1; Application.DoEvents();
                toolStripStatusLabel1.Text = "进度：" + (r + 1) + "/" + dataGridView1.RowCount;
            }
            ProgressBar_finish();


            Thread.Sleep(60000); // 延迟60秒
            for (int i = 0; i < list.Count; i++)
            {
                dataGridView1.Rows[i].Cells[2].Value = list[i];
            }

        }
        private void button2_Click(object sender, EventArgs e)//打开表格
        {
            OpenFileDialog fd = new OpenFileDialog { Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls" };
            string strpath;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    strpath = fd.FileName;
                    //string strCon = "provider=microsoft.jet.oledb.4.0;data source=" + strpath + ";extended properties=excel 8.0";//32位平台
                    //string strCon = "provider=microsoft.ACE.OLEDB.12.0" + strpath + ";extended properties=excel 8.0";//需要安装Access Data engin数据库引擎
                    string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strpath + ";Extended Properties=\"Excel 12.0;HDR=YES\"";//64位平台可用

                    OleDbConnection Con = new OleDbConnection(strCon);
                    string strSql = "select* from [Sheet1$]";
                    OleDbCommand cmd = new OleDbCommand(strSql, Con);
                    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    dataGridView1.DataSource = dt;

                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }// + "(需使用Excel 2003.xls版本)"               
            }
        }
        private void button3_Click(object sender, EventArgs e)//保存表格
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "Excel|*.xlsx|Excel|*.xls"
            };
            if (saveFileDialog.ShowDialog() == DialogResult.OK && saveFileDialog.FileName != "")
            {
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                if (xlApp == null) { MessageBox.Show("无Excel"); return; }

                Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
                Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.Worksheets[1];

                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
                }
                //写入数值
                ProgressBar_initialize(dataGridView1.RowCount);
                for (int r = 0; r < dataGridView1.RowCount; r++)
                {
                    for (int i = 0; i < dataGridView1.ColumnCount; i++)
                    {
                        worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
                    }
                    ProgressBar_Number(r, dataGridView1.RowCount);
                }
                worksheet.Columns.EntireColumn.AutoFit();

                ProgressBar_finish(); MessageBox.Show("资料保存成功");
                workbook.Saved = true;
                workbook.SaveCopyAs(saveFileDialog.FileName);
                xlApp.Quit();
                this.Close();
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {  
            //获得问题
            string question = $"根据存货编码表格里的存货代码和规格型号，找到        的对应编码，直接输出存货编码的结果值就行，无需进行其他描述";

            //获得回答
            //Deepseek.Deepseek_API("SOLIDWORKS CAM 技术数据库(TechDB)负表定义和选择加工工具。(对或错)");
            Coze.Coze1(question);
            
            //显示回答
            MessageBox.Show(Coze.answer);
        }

        //——————★进度条操作——————//
        private void ProgressBar_initialize(int length)//进度条初始化
        {
            toolStripProgressBar1.Value = 0;
            toolStripStatusLabel1.Text = "进度： ";
            toolStripProgressBar1.Maximum = length;
        }
        private void ProgressBar_finish()//进度条完成
        {
            toolStripStatusLabel1.Text = "进度：完成";
            toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
        }
        private void ProgressBar_Number(int i, int length)//数字进度条
        {
            toolStripProgressBar1.Value += 1;
            toolStripStatusLabel1.Text = "进度：" + (i + 1) + "/" + length; ; Application.DoEvents();
        }


        //——————★进度条操作——————//
        public static string answer;
        public static async void Coze_API(string question)//发起对话(流式 stream = true,)
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer pat_20D4Uu1hM5b5lYFijNp3vORK3gG7nIP7f7k1cVnSheMVSbR3oUtAfZAf8jveXZyM");
            var requestData = new
            {
                auto_save_history = true,
                stream = true,
                user_id = "me",
                bot_id = "7489376497380343820",
                additional_messages = new[]
                {
                    new{
                            role= "user" ,
                            content=question
                        }
                    }
            };//请求参数

            var jsonContent = JsonConvert.SerializeObject(requestData);//转换成json格式
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await client.PostAsync($"https://api.coze.cn/v3/chat?", content);
            dynamic responseContet = await response.Content.ReadAsStringAsync();

            dynamic result = JsonConvert.DeserializeObject(responseContet);

            string str_chat_id = result.data.id;
            string str_conversation_id = result.data.conversation_id; ;

            Coze2(str_chat_id, str_conversation_id);

        }
        public static async void Coze1(string question)//发起对话(非流式 stream = false,)
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer pat_20D4Uu1hM5b5lYFijNp3vORK3gG7nIP7f7k1cVnSheMVSbR3oUtAfZAf8jveXZyM");
            var requestData = new
            {
                auto_save_history = true,
                stream = false,
                user_id = "me",
                bot_id = "7489376497380343820",
                additional_messages = new[]
                {
                    new{
                            role= "user" ,
                            content=question
                        }
                    }
            };//请求参数

            var jsonContent = JsonConvert.SerializeObject(requestData);//转换成json格式
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await client.PostAsync($"https://api.coze.cn/v3/chat?", content);
            dynamic responseContet = await response.Content.ReadAsStringAsync();

            dynamic result;
            try
            {
                result = JsonConvert.DeserializeObject(responseContet);
            }
            catch (Exception)
            {
                answer = "-"; list.Add(answer);
                throw;
            }

            string str_chat_id = result.data.id;
            string str_conversation_id = result.data.conversation_id; ;

            Coze2(str_chat_id, str_conversation_id);

        }
        private static async void Coze2(string str_chat_id, string str_conversation_id)//查看对话详情
        {
            Thread.Sleep(2000); // 延迟3秒

            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"https://api.coze.cn/v3/chat/retrieve?conversation_id={str_conversation_id}&chat_id={str_chat_id}&");

            request.Headers.Add("Authorization", "Bearer pat_20D4Uu1hM5b5lYFijNp3vORK3gG7nIP7f7k1cVnSheMVSbR3oUtAfZAf8jveXZyM");

            request.Content = new StringContent("");
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            dynamic result = JsonConvert.DeserializeObject(responseBody);
            string status;
            try
            {
                status = result.data.status;
            }
            catch (Exception)
            {
                answer = "-"; list.Add(answer);
                throw;
            }
            if (status != "completed")
            {
                Coze2(str_chat_id, str_conversation_id);
            }
            else
            {
                Coze3(str_chat_id, str_conversation_id);
            }
        }
        private static async void Coze3(string str_chat_id, string str_conversation_id)//查看对话消息详情
        {
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"https://api.coze.cn/v3/chat/message/list?conversation_id={str_conversation_id}&chat_id={str_chat_id}&");

            request.Headers.Add("Authorization", "Bearer pat_20D4Uu1hM5b5lYFijNp3vORK3gG7nIP7f7k1cVnSheMVSbR3oUtAfZAf8jveXZyM");

            request.Content = new StringContent("");
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            dynamic result = JsonConvert.DeserializeObject(responseBody);

            try
            {
                answer = result.data[1].content;//Console.WriteLine(answer);
            }
            catch (Exception)
            {
                answer = "-";
            }
            Console.WriteLine(answer); list.Add(answer);
        }


    }
}

